package at.fhj.itm11.forum.beans;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

import at.fhj.itm11.forum.service.TopicService;
import at.fhj.itm11.forum.service.dtos.TopicDTO;
import at.fhj.itm11.forum.service.dtos.UserDTO;
import at.fhj.itm11.forum.util.ForumConstants;

@Named
@ManagedBean
@RequestScoped
public class TopicBean {

	@Inject
	@Named("authenticationBean")
	private AuthenticationBean authBean;

	@Inject
	@Named("topicServiceImpl")
	private TopicService topicService;

	private HttpSession session;
	private TopicDTO topic;

	@PostConstruct
	public void init() {
		session = (HttpSession) authBean.getSession();
		topic = new TopicDTO();
	}

	public void register() throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();
		try {

			UserDTO author = (UserDTO) session.getAttribute(
					ForumConstants.SESSION_CURRENT_USER);

			// check is user is logged in
			if (author == null) {
				context.addMessage(null, new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Please log in first!",
						null));
				// check for empty title
			} else if (topic.getIcon() == null || "".equals(topic.getIcon())) {
				context.addMessage("reg:icon", new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Creation failed",
						"Icon must not be empty!"));
			} else if (topic.getTitle() == null || "".equals(topic.getTitle())) {
				context.addMessage("reg:title", new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Creation failed",
						"Title must not be empty!"));
			} else if (topic.getDescription() == null
					|| "".equals(topic.getDescription())) {
				context.addMessage("reg:description", new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Creation failed",
						"Description must not be empty!"));
			} else {
				topicService.register(topic, author,  new Date());
				context.addMessage(null, new FacesMessage(
						FacesMessage.SEVERITY_INFO,
						"Topic creation successful!", "Creation successful"));
				setCurrentTopic(topic);
			}
		} catch (Exception e) {
			String errorMessage = getRootErrorMessage(e);
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, errorMessage,
					"Creation failed"));
		}
	}

	private String getRootErrorMessage(Exception e) {
		// Default to general error message that registration failed.
		String errorMessage = "Registration failed. See server log for more information";
		if (e == null) {
			// This shouldn't happen, but return the default messages
			return errorMessage;
		}

		// Start with the exception and recurse to find the root cause
		Throwable t = e;
		while (t != null) {
			// Get the message from the Throwable class instance
			errorMessage = t.getLocalizedMessage();
			t = t.getCause();
		}
		// This is the root cause message
		return errorMessage;
	}

	public TopicDTO getCurrentTopic() {
		return (TopicDTO) session
				.getAttribute(ForumConstants.SESSION_CURRENT_TOPIC);
	}

	public void setCurrentTopic(TopicDTO currentTopic) {
		if (currentTopic == null) {
			throw new IllegalArgumentException();
		}
		session.setAttribute(ForumConstants.SESSION_CURRENT_TOPIC, currentTopic);
	}

	public List<TopicDTO> getTopics() {
		return topicService.retrieveAllTopicsOrderedByTitle();
	}

	public TopicDTO getTopic() {
		return topic;
	}

	public void setTopic(TopicDTO topic) {
		this.topic = topic;
	}
	
	public void setSession(HttpSession session) {
		this.session = session;
	}

}